﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Molia.AppCenter.Service
{
    public static class MessageService
    {
        struct RefObject
        {
            public IMessageAcceptable Refference;
            public Type Type;
            public string Filter;
        }
        static List<RefObject> ObjPool = new List<RefObject>();

        public static void Registry(Type AcceptTargetType, IMessageAcceptable Acceptor, string Filter)
        {
            bool find=false;
            foreach(var i in ObjPool)
            {
                if(Filter==i.Filter&&i.Refference.Equals(Acceptor))
                {
                    find = true;
                    break;
                }
            }
            if (!find)
            {
                ObjPool.Add(new RefObject()
                {
                    Type = AcceptTargetType,
                    Refference = Acceptor,
                    Filter = Filter
                });
                System.Diagnostics.Debug.WriteLine("当前有一个对象注册到了消息池当中 {0}",Acceptor.ToString());
            }
            else
            {
                throw new Exception("已经存在该对象");
            }
        }
        public static void SendMessage(Type type, object data, string Filter)
        {
            var queue = from item in ObjPool where item.Filter == Filter && item.Type.Equals(type) select item;
            System.Diagnostics.Debug.WriteLine("当前有一个对象调用了消息传递，获得的注册对象有{0}", queue.Count<RefObject>());
            foreach (var i in queue)
            {
                i.Refference.InvokeMessage(data,Filter);
            }
        }
        public static void UnRegistry(Type AcceptTargetType, IMessageAcceptable Acceptor, string Filter)
        {
            var n = new RefObject()
            {
                Filter = Filter,
                Refference = Acceptor,
                Type = AcceptTargetType
            };
            foreach(var i in ObjPool)
            {
                if(i.Equals(n))
                {
                    ObjPool.Remove(i);
                }
            }
        }
    }
}
